package com.example.seh.chat;


import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.seh.R;
import com.example.seh.UserDTO;
import com.example.seh.constant.Constant;
import com.example.seh.home.secondhand.GoodsDTO;
import com.example.seh.home.substitution.CourierSuccessActivity;
import com.example.seh.util.BackUtil;
import com.example.seh.util.ChatClient;
import com.example.seh.util.ChatServer;
import com.example.seh.util.ChatUtil;
import com.example.seh.util.ImgUtil;
import com.example.seh.util.PhoneUtil;
import com.example.seh.util.UserMsg;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ChatActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static List<Msg> msgList = new ArrayList<>();
    private List<Bitmap> bitmapList = new ArrayList<>();
    private static RecyclerView msgRecyclerView;
    private static EditText inputText;
    private Button send, add, sendImg, delImg;
    private LinearLayoutManager layoutManager;
    private static MsgAdapter adapter;
    private RelativeLayout chooseImg;
    private boolean isChooseImg = false;
    private ImageButton imgBtn;
    private Intent openCamera;//打开相册intent
    private final int CHOOSE = 2;
    private ImageView img;
    private Bitmap sendBitmap;
    private TextView name;
    private CircleImageView avatar;
    private ImageView phoneBtn;
    private GoodsDTO goodsDTO;
    private UserDTO userDTO;
    private static int fromId;
    private static int toId;
    final ChatServer chatServer = null;
    final ChatClient chatClient = new ChatClient();
    static ChatClient chatClientImg = new ChatClient();
    private String myAddress = null;
    private static String youAddress = null;
    private static File file;
    private static String image;
    private String phoneNum = "";
    public static Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1://发送消息，添加到消息list并显示
                    System.out.println("新输入的内容：" + msg.obj);
                    String myMsg = (String) msg.obj;
                    if(!"".equals(myMsg)) {
                        ChatUtil.msgList.add(new Msg(fromId, toId, myMsg, null, Msg.MSG));
                        msgList.add(new Msg(fromId, toId, myMsg, null, Msg.MSG));
//                        adapter.notifyItemInserted(msgList.size()-1);
                        adapter.notifyDataSetChanged();
                        msgRecyclerView.scrollToPosition(msgList.size()-1);
                        sendMsg(myMsg);
                        Log.e("chat","发送完消息后msgList大小：" + msgList.size());
                        Log.e("chat","发送完消息后msgList：" + msgList.toString());

                        inputText.setText("");//清空输入框中的内容
                    }
                    break;
                case 2:
                    if (ChatUtil.msgCache.size() != 0) {//接收消息，刚点开聊天界面，有缓存消息，显示
                        ChatUtil.msgList.addAll(ChatUtil.msgCache);
                        msgList = ChatUtil.msgList;
//                        adapter.notifyItemRangeInserted(0, msgList.size());
                        adapter.notifyDataSetChanged();
                        msgRecyclerView.scrollToPosition(ChatUtil.msgList.size() + ChatUtil.msgCache.size() - 1);
                        ChatUtil.msgCache.clear();//缓存消息显示完成后清空缓存
                    } else {
                        if (Constant.isFirstChat) {//刚打开聊天界面还未聊天，显示所有历史信息
                            Log.e("chat","刚进入时ChatUtil.msgList大小：" + msgList.size());
                            Log.e("chat","刚打开聊天界面还未聊天，显示所有历史信息");
                            msgList.addAll(ChatUtil.msgList);
                            adapter.notifyDataSetChanged();
//                            adapter.notifyItemRangeInserted(0, msgList.size());
                            msgRecyclerView.scrollToPosition(msgList.size() - 1);
                            Log.e("chat",msgList.toString());
                            Log.e("chat","刚进入时msgList大小：" + msgList.size());


                            Constant.isFirstChat = false;
                        } else {//已经打开聊天界面且历史信息加载完成，再有消息则实时更新
                            Log.e("chat","已经打开聊天界面且历史信息加载完成，再有消息则实时更新");
                            msgList.add(ChatUtil.msgList.get(ChatUtil.msgList.size()-1));
//                            adapter.notifyItemInserted(msgList.size()-1);
                            adapter.notifyDataSetChanged();
                            msgRecyclerView.scrollToPosition(msgList.size()-1);
                            Log.e("chat","ChatUtil.msgList:" + ChatUtil.msgList.toString());

                        }
                    }
                    break;
                case 3:
                    sendImg();
                    break;
                case 4:
                    Log.e("cimg","展示图片img");
                    ChatUtil.msgList.add(new Msg(fromId, toId, null, image, Msg.IMG));
                    msgList.add(new Msg(fromId, toId, null, image, Msg.IMG));
                    adapter.notifyDataSetChanged();
                    msgRecyclerView.scrollToPosition(msgList.size()-1);
                    Log.e("cimg","展示图片完成");
                    sendImgByImage();
                    break;
//                case 5:

            }

        }
    };




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        System.out.println("新打开的聊天界面");
        PhoneUtil.getPermission(ChatActivity.this);
        getViews();

        layoutManager = new LinearLayoutManager(this);
        msgList = getData();
        adapter = new MsgAdapter(ChatActivity.this, msgList);

        msgRecyclerView.setLayoutManager(layoutManager);
        msgRecyclerView.setAdapter(adapter);

        setDatas();
        setListeners();
        setSocket();
    }
    private static void sendImgByImage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

//            Message message = new Message();
//            message.what = 5;
//            handler.sendMessage(message);


                    Socket socket = chatClientImg.requestSocket(youAddress);
                    socket.setKeepAlive(true);
                    socket.setSoTimeout(10);
                    socket.sendUrgentData(0xFF);
                    chatClientImg.sendMsg(socket, image);


                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
    private static void sendImg() {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String nowTime  = formatter.format(curDate);

        OkHttpClient okHttpClient = new OkHttpClient();
        MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
        requestBodyBuilder
                .addFormDataPart("fromId", fromId + "")
                .addFormDataPart("toId", toId + "")
                .addFormDataPart("file", file.getName(), requestBody)
                .addFormDataPart("msgOrImgType", Msg.IMG + "")
                .addFormDataPart("sendTime", nowTime);

        RequestBody body = requestBodyBuilder.build();

        Request request = new Request.Builder()
                .url(Constant.SENDIMG)
                .header("Content-Type", "multipart/form-data")
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("cimg","图片保存失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                String msg = result.substring(1,result.length() - 1);
                String data = null;
                try {
                    JSONObject jsonObject = new JSONObject(msg);
                    data = jsonObject.getString("data");

                    Log.e("cimg","新发送的图片：" + data);
                    image = data;
                    Message message = new Message();
                    message.what = 4;
                    handler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                Log.e("cimg",result);
                if ("上传成功!".equals(data)) {
                    Log.e("cimg","图片保存成功");
                }
            }
        });
    }

    private static void sendMsg(String txt) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String nowTime  = formatter.format(curDate);

        OkHttpClient okHttpClient = new OkHttpClient();
        JSONObject object = new JSONObject();
        try {
            object.put("fromId", fromId);
            object.put("toId", toId);
            object.put("message", txt);
            object.put("msgOrImgType", Msg.MSG);
            object.put("sendTime", nowTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MediaType type = MediaType.parse("application/json;charset=utf-8");
        Log.e("chat", object.toString());
        RequestBody body = RequestBody.create(type, "" + object.toString());

        Request request = new Request.Builder()
                .url(Constant.SENDMSG)
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("chat","消息保存失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e("chat",result);
                if ("添加成功".equals(result)) {
                    Log.e("chat","消息保存成功");
                }
            }
        });
    }

    private void setDatas() {
        Intent intent = getIntent();
        //如果是从商品详情页进入聊天界面      从我的商品-我买到的进入聊天界面
        if (intent.getSerializableExtra("buniess") != null) {
            goodsDTO = (GoodsDTO) intent.getSerializableExtra("buniess");
            Log.e("bought", "goodsDTO:" + goodsDTO.toString());
            fromId = UserMsg.userDTO.getUserId();
            toId = goodsDTO.getUserDTO().getUserId();
            youAddress = goodsDTO.getUserDTO().getIpAddress();
            phoneNum = goodsDTO.getUserDTO().getPhone();
            Log.e("chatlist","goods-youaddress:" + youAddress);
            if (goodsDTO != null) {
                if (goodsDTO.getUserDTO().getPic() != null) {
                    try {
//                        avatar.setImageBitmap(ImgUtil.setUserAvatar(goodsDTO.getUserDTO().getPic()));
                        Glide.with(ChatActivity.this).load(goodsDTO.getUserDTO().getPic()).into(avatar);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        avatar.setImageBitmap(ImgUtil.setDefaultAvatar(getApplicationContext(), R.mipmap.default_avatar2));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                name.setText(goodsDTO.getUserDTO().getUsername());
//            youAddress = goodsDTO.getUserDTO().getIpAddress();
//            youAddress = "192.168.137.174";

            }
        } else if (intent.getSerializableExtra("user") != null){
            //从消息界面点击进入聊天界面,   从我的商品-我的代取进入
            userDTO = (UserDTO) intent.getSerializableExtra("user");
            fromId = UserMsg.userDTO.getUserId();
            toId = userDTO.getUserId();
            youAddress = userDTO.getIpAddress();
            phoneNum = userDTO.getPhone();
            Log.e("chatlist","user-youaddress:" + youAddress);
            if (userDTO != null) {
                if (!"".equals(userDTO.getPic())) {
                    try {
//                        avatar.setImageBitmap(ImgUtil.setUserAvatar(userDTO.getPic()));
                        Glide.with(ChatActivity.this).load(userDTO.getPic()).into(avatar);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        avatar.setImageBitmap(ImgUtil.setDefaultAvatar(getApplicationContext(),R.mipmap.default_avatar2));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                name.setText(userDTO.getUsername());
            }
        }


//        youAddress = "10.0.2.16";
        //进入聊天界面，向后端发出请求，获取聊天记录，并赋值给ChatUtil.msgList
        //根据Constant.isChat判断是否打开聊天界面,如果true，读取msgList中的消息并显示
        Constant.isChat = true;//打开聊天界面
        getChatData();


//        if (Constant.isChat) {
//            Message message = new Message();
//            message.what = 2;
//            handler.sendMessage(message);
//        }

    }

    private void getChatData() {
        Log.e("selectchat","fromId=" + fromId + "&toId=" + toId);
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.FINDMSG + "fromId=" + fromId + "&toId=" + toId)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("chatlist","聊天记录加载失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e("chatlist",result);
                Gson gson = new Gson();
                Type type = new TypeToken<List<Msg>>(){}.getType();
                List<Msg> list = gson.fromJson(result,type);
                Log.e("chatlist",list.toString());
                ChatUtil.msgList = list;
                Message message = new Message();
                message.what = 2;
                handler.sendMessage(message);
            }
        });
    }

    private void setSocket() {
        myAddress = ChatUtil.getIPAddress(ChatActivity.this);
//        youAddress = "192.168.137.149";
        Log.e("chat", "myaddress:" + myAddress);
        //        初始化看是服务器
//        try {
//            ChatServer chatServer = new ChatServer();
//            chatServer.start();
//            Log.e("chat", "开启服务器成功");
//        } catch (IOException e) {
//            Log.e("chat", "开启服务器失败");
//            e.printStackTrace();
//        }


    }

    private void setListeners() {
        /*       我们还需要为button建立一个监听器，我们需要将编辑框的内容发送到 RecyclerView 上：
            ①获取内容，将需要发送的消息添加到 List 当中去。
            ②调用适配器的notifyItemInserted方法，通知有新的数据加入了，赶紧将这个数据加到 RecyclerView 上面去。
            ③调用RecyclerView的scrollToPosition方法，以保证一定可以看的到最后发出的一条消息。*/
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!"".equals(inputText.getText().toString())) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                String msg = "";
                                Message message1 = new Message();
                                message1.what = 1;
                                message1.obj = inputText.getText().toString();
                                msg = inputText.getText().toString();
                                Log.e("chat", "正在发送信息");
                                handler.sendMessage(message1);

                                Socket socket = chatClient.requestSocket(youAddress);
                                socket.setKeepAlive(true);
                                socket.setSoTimeout(10);
                                socket.sendUrgentData(0xFF);
                                Log.e("chat", "输入框内容：" + msg);
                                chatClient.sendMsg(socket, msg);


                                socket.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                                Log.e("错误", "发送失败");
                                Log.e("chat", e.toString());
                            }
                        }
                    }).start();
                } else {
                    Toast.makeText(getApplicationContext(), "请输入内容", Toast.LENGTH_SHORT).show();
                }

            }
        });
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isChooseImg) {
                    isChooseImg = true;
                    chooseImg.setVisibility(View.VISIBLE);
                    add.setText("×");
                } else {
                    isChooseImg = false;
                    chooseImg.setVisibility(View.GONE);
                    add.setText("+");
                }
            }
        });
        imgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openCamera = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(openCamera, CHOOSE);
            }
        });
        sendImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sendBitmap == null) {
                    Toast.makeText(getApplicationContext(), "请先选择图片", Toast.LENGTH_SHORT).show();
                } else {
                    System.out.println("新选择的图片：" + sendBitmap);
                    if(sendBitmap != null) {
                        Message message = new Message();
                        message.what = 3;
                        handler.sendMessage(message);


                        Log.e("cimg",ChatUtil.msgList.toString());
                        sendBitmap = null;
                        img.setImageBitmap(null);//清空输入框中的内容
                    }
                }
            }
        });

        delImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (img.getDrawable() != null) {
                    img.setImageBitmap(null);
                    sendBitmap = null;
                }
            }
        });

        phoneBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                PhoneUtil.toPhone(getApplicationContext(), phoneNum);
            }
        });
    }

    private List<Msg> getData(){
        List<Msg> list = new ArrayList<>();
//        list.add(new Msg("Hello", null, Msg.TYPE_RECEIVED, Msg.MSG));
        return list;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CHOOSE:
                if (resultCode == RESULT_OK) {
                    try {
                        Uri uri = data.getData();
//                        returnUriString = uri.toString();
//                        photoPath = PathHelper.getRealPathFromUri(MainActivity.this, uri);
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                        Log.i("msg","src:" + uri.toString());
                        //压缩图片
                        bitmap = ImgUtil.scaleBitmap(bitmap, (float) 0.5);
                        sendBitmap = bitmap;
                        file = ImgUtil.uriToFile( Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null,null)),ChatActivity.this);
                        //预览图片
                        img.setImageBitmap(bitmap);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }
    private void getViews() {
        avatar = findViewById(R.id.chat_avatar);
        msgRecyclerView = findViewById(R.id.msg_recycler_view);
        inputText = findViewById(R.id.input_text);
        send = findViewById(R.id.send);
        add = findViewById(R.id.add);
        chooseImg = findViewById(R.id.choose_img);
        imgBtn = findViewById(R.id.send_img);
        img = findViewById(R.id.img_show);
        sendImg = findViewById(R.id.send_img_btn);
        delImg = findViewById(R.id.send_img_btn_del);
        name = findViewById(R.id.buniess_name);
        phoneBtn = findViewById(R.id.buniess_phone);
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Constant.isChat = false;
            Constant.isFirstChat = true;
            ChatUtil.youAvatar = null;
        }
        ChatUtil.msgList.clear();
        finish();

        return true;
    }
}